package org.jeecg.modules.tm.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.BaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.tm.entity.TmTunnelCheck;
import org.jeecg.modules.tm.entity.TmTunnelCheckDetail;
import org.jeecg.modules.tm.entity.TmTunnelDiseaseCategory;
import org.jeecg.modules.tm.service.ITmTunnelCheckDetailService;
import org.jeecg.modules.tm.service.ITmTunnelCheckService;
import org.jeecg.modules.tm.service.ITmTunnelDiseaseCategoryService;
import org.jeecg.modules.tm.service.ITmTunnelService;
import org.jeecg.modules.tm.vo.TunnelCheckDetailVO;
import org.jeecg.modules.tm.vo.TunnelCheckInsertVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 隧道定检
 * @@author 品讯科技
 * @Date: 2024-02-04
 * @Version: V1.0
 */
@Api(tags = "隧道定检")
@RestController
@RequestMapping("/tm/tmTunnelCheck")
@Slf4j
public class TmTunnelCheckController extends BaseController<TmTunnelCheck, ITmTunnelCheckService> {

    @Autowired
    private ITmTunnelCheckService tmTunnelCheckService;
    @Autowired
    private ITmTunnelCheckDetailService tmTunnelCheckDetailService;
    @Autowired
    private ITmTunnelDiseaseCategoryService tmTunnelDiseaseCategoryService;

    /**
     * 分页列表查询
     *
     * @param tmTunnelCheck
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "隧道定检-分页列表查询")
    @ApiOperation(value = "隧道定检-分页列表查询", notes = "隧道定检-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<TmTunnelCheck>> queryPageList(TmTunnelCheck tmTunnelCheck,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<TmTunnelCheck> queryWrapper = QueryGenerator.initQueryWrapper(tmTunnelCheck, req.getParameterMap());
        Page<TmTunnelCheck> page = new Page<TmTunnelCheck>(pageNo, pageSize);
        IPage<TmTunnelCheck> pageList = tmTunnelCheckService.page(page, queryWrapper);

        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            for (TmTunnelCheck record : pageList.getRecords()) {
                LambdaQueryWrapper<TmTunnelCheckDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(TmTunnelCheckDetail::getTunnelCheckId, record.getId());
                lambdaQueryWrapper.ne(TmTunnelCheckDetail::getStateNum, 0);
                List<TmTunnelCheckDetail> totalList = this.tmTunnelCheckDetailService.list(lambdaQueryWrapper);
                long count = totalList.stream().filter(item -> item.getState().equals("0")).count();
                record.setTotalNum(totalList.size());
                record.setNum0(count);
                record.setNum1(totalList.size() - count);
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param tmTunnelCheck
     * @return
     */
    @AutoLog(value = "隧道定检-添加")
    @ApiOperation(value = "隧道定检-添加", notes = "隧道定检-添加")
    //@RequiresPermissions("tm:tm_tunnel_check:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody TmTunnelCheck tmTunnelCheck) {
        tmTunnelCheckService.save(tmTunnelCheck);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param tmTunnelCheck
     * @return
     */
    @AutoLog(value = "隧道定检-编辑")
    @ApiOperation(value = "隧道定检-编辑", notes = "隧道定检-编辑")
    //@RequiresPermissions("tm:tm_tunnel_check:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody TmTunnelCheck tmTunnelCheck) {
        tmTunnelCheckService.updateById(tmTunnelCheck);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "隧道定检-通过id删除")
    @ApiOperation(value = "隧道定检-通过id删除", notes = "隧道定检-通过id删除")
    //@RequiresPermissions("tm:tm_tunnel_check:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        tmTunnelCheckService.remove(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "隧道定检-批量删除")
    @ApiOperation(value = "隧道定检-批量删除", notes = "隧道定检-批量删除")
    //@RequiresPermissions("tm:tm_tunnel_check:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            tmTunnelCheckService.remove(id);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "隧道定检-通过id查询")
    @ApiOperation(value = "隧道定检-通过id查询", notes = "隧道定检-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<TmTunnelCheck> queryById(@RequestParam(name = "id", required = true) String id) {
        TmTunnelCheck tmTunnelCheck = tmTunnelCheckService.getById(id);
        if (tmTunnelCheck == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(tmTunnelCheck);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param tmTunnelCheck
     */
    //@RequiresPermissions("tm:tm_tunnel_check:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TmTunnelCheck tmTunnelCheck) {
        return super.exportXls(request, tmTunnelCheck, TmTunnelCheck.class, "隧道定检");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("tm:tm_tunnel_check:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TmTunnelCheck.class);
    }


    /**
     * 一键处治
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "隧道定检-一键处治", notes = "隧道定检-一键处治")
    @GetMapping(value = "/handleHot/{id}")
    public Result<String> handleHot(@PathVariable(name = "id") String id) {
        TmTunnelCheck tmTunnelCheck = tmTunnelCheckService.getById(id);
        if (tmTunnelCheck == null) {
            return Result.error("未找到对应数据");
        }
        tmTunnelCheckService.handleHot(id);
        return Result.OK("处治成功");
    }


    /**
     * 完成状态
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "隧道定检-完成状态", notes = "隧道定检-完成状态")
    @GetMapping(value = "/state/{id}")
    public Result<String> updateState(@PathVariable(name = "id") String id) {
        TmTunnelCheck tmTunnelCheck = tmTunnelCheckService.getById(id);
        if (tmTunnelCheck == null) {
            return Result.error("未找到对应数据");
        }
        tmTunnelCheck.setState("1");
        tmTunnelCheckService.updateById(tmTunnelCheck);
        return Result.OK("处治成功");
    }


    /**
     * 导入定检明细
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelDetail", method = RequestMethod.POST)
    public Result<String> importExcelDetail(HttpServletRequest request, HttpServletResponse response) {

        String tunnelCheckId = request.getParameter("tunnelCheckId");
        if (StrUtil.isBlank(tunnelCheckId)) {
            return Result.error("请选择具体的定检路线！");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setSheetNum(1);
            params.setNeedSave(true);
            try {
                List<TunnelCheckDetailVO> list = ExcelImportUtil.importExcel(file.getInputStream(), TunnelCheckDetailVO.class, params);
                if (CollectionUtils.isEmpty(list)) {
                    return Result.error("文件中未找到数据！");
                }

                List<TmTunnelDiseaseCategory> tunnelDiseaseCategoryList = tmTunnelDiseaseCategoryService.list();

                //过滤空白后的数据
                List<TunnelCheckDetailVO> filterList = list.stream().filter(item -> StrUtil.isNotBlank(item.getRealNum())).collect(Collectors.toList());
                //保存入库数据
                List<TunnelCheckInsertVO> insertList = new ArrayList<>();

                TunnelCheckInsertVO tunnelCheckInsertVO = null;
                for (TunnelCheckDetailVO tunnelCheckDetailVO : filterList) {

                    //装载数据
                    if (StrUtil.isNotBlank(tunnelCheckDetailVO.getCheckName())) {
                        tunnelCheckInsertVO = new TunnelCheckInsertVO();
                        TmTunnelCheck tmTunnelCheck = new TmTunnelCheck();
                        BeanUtils.copyProperties(tunnelCheckDetailVO, tmTunnelCheck);
                        tunnelCheckInsertVO.setTmTunnelCheck(tmTunnelCheck);
                        List<TmTunnelCheckDetail> tmTunnelCheckDetailList = new ArrayList<>();
                        tunnelCheckInsertVO.setTmTunnelCheckDetailList(tmTunnelCheckDetailList);
                        insertList.add(tunnelCheckInsertVO);
                    }
                    //装载明细
                    if (tunnelCheckInsertVO != null) {
                        TmTunnelCheckDetail tunnelCheckDetail = new TmTunnelCheckDetail();
                        BeanUtils.copyProperties(tunnelCheckDetailVO, tunnelCheckDetail);
                        //设置处理状态为未处理
                        tunnelCheckDetail.setState("0");
                        //设置分类
                        tunnelCheckDetail.setCategoryId(getCategory(tunnelCheckDetail.getPart(), tunnelCheckDetail.getDiseaseName(), tunnelDiseaseCategoryList));
                        tunnelCheckInsertVO.getTmTunnelCheckDetailList().add(tunnelCheckDetail);
                    }
                }
                //插入或者更新数据，需要把检测ID一起带入
                tmTunnelCheckService.saveDetail(tunnelCheckId, insertList);
                //自动保存文件
                this.saveImportFile(file, "隧道定检明细");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 自动识别归属类型
     *
     * @param part
     * @param diseaseName
     * @param tunnelDiseaseCategoryList
     * @return
     */
    private String getCategory(String part, String diseaseName, List<TmTunnelDiseaseCategory> tunnelDiseaseCategoryList) {

        if (StrUtil.isBlank(part)) {
            return "-1";
        }
        List<TmTunnelDiseaseCategory> resultList = new ArrayList<>();
        for (TmTunnelDiseaseCategory tmTunnelDiseaseCategory : tunnelDiseaseCategoryList) {
            if (tmTunnelDiseaseCategory.getPart().indexOf(part) > -1) {
                resultList.add(tmTunnelDiseaseCategory);
            }
        }

        if (resultList.size() == 0) {
            //说明没有匹配的数据
            return "-1";
        } else if (resultList.size() == 1) {
            //找到一个分类信息，则直接返回分类信息即可
            return resultList.get(0).getCategoryId();
        } else {
            if (StrUtil.isBlank(diseaseName)) {
                //如果病害名称不存在则直接返回第一个查找到的结果分类
                return resultList.get(0).getCategoryId();
            }
            //找到多个分类信息，继续查找，根据病害名称进行查找和关键字查找
            for (TmTunnelDiseaseCategory tmTunnelDiseaseCategory : resultList) {
                boolean b = (StrUtil.isNotBlank(tmTunnelDiseaseCategory.getDiseaseName()) && tmTunnelDiseaseCategory.getDiseaseName().indexOf(diseaseName) > -1) ||
                        (StrUtil.isNotBlank(tmTunnelDiseaseCategory.getDiseaseLike()) && diseaseName.indexOf(tmTunnelDiseaseCategory.getDiseaseLike()) > -1);
                if (b) {
                    return tmTunnelDiseaseCategory.getCategoryId();
                }
            }
        }
        return "-1";
    }

    /**
     * 获取分类ID
     *
     * @param part
     * @param diseaseName
     * @return
     */
    @Deprecated
    private String getCategory(String part, String diseaseName) {
        if ("洞口".equals(part)) {
            //洞口工程
            return "1";
        } else if ("洞门".equals(part)) {
            //洞门
            return "2";
        } else if ("衬砌".equals(part)) {
            String str3 = "防水板外露|钢筋外露|环向裂缝|环向裂缝(伴结晶)|环向裂缝(伴渗水)|破损|网状裂缝|斜向裂缝|锈胀露筋|纵向裂缝|纵向裂缝(伴结晶)";
            String str4 = "点状渗水干渍|点状渗水干渍、结晶|面状渗水干渍|面状渗水干渍、结晶|面状渗水结晶、湿渍|面状渗水湿渍|施工缝渗水干渍|施工缝渗水干渍、结晶|线状渗水干渍|线状渗水干渍、结晶|线状渗水结晶、湿渍|线状渗水湿渍、结晶";
            if (str3.contains(diseaseName)) {
                //表层缺陷
                return "3";
            } else if (str4.contains(diseaseName) || (StrUtil.isNotBlank(diseaseName) && diseaseName.indexOf("渗水") > -1)) {
                //渗漏水
                return "4";
            }
        } else if ("检修道".equals(part)) {
            //检修道
            return "5";
        } else if ("排水设施|排水系统".contains(part)) {
            //排水系统
            return "6";
        } else if ("路面".equals(part)) {
            //路面病害
            return "7";
        } else if ("吊顶及各种预埋件".equals(part)) {
            //吊顶及预埋件病害
            return "8";
        } else if ("交通标志，标线、轮廓标".equals(part)) {
            //标志
            return "9";
        } else if ("标志、标线、轮廓标".equals(part)) {
            //标线
            return "10";
        }
        return "-1";
    }


}
